<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */


include_once( APP . "Config/your_define.php" );
App::uses('Sanitize', 'Utility');
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	var $helpers = array('Html', 'Paginator', 'Session', 'Js', 'Form', 'Cache', 'Text', 'Time');
    var $components = array('Acl', 'Session', "Email", 'Auth', 'RequestHandler', 'Cookie', 'Common', "File"); //,

    var $als = '';

    /**
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function beforeFilter() {
		if(!isset($_SESSION)) {
		     session_start();
		}

		$params = $this->request->params;

		$this->set('action', $params['action']);
		$this->set('controller', $params['controller']);

		App::uses('Category', 'Model');
		$Category = new Category();
		
		$user = $this->Auth->user();
		$this->set('global_user', $user);

		if( isset($params['prefix']) && $params['prefix'] == 'admin') {
			$this->layout = 'admin';

			// Get tin nhắn mới
			App::uses('Message', 'Model');
			$Message = new Message();
			$messages = $Message->getAll(array(0));
			if(!empty($messages))
	        foreach($messages as $k => $v) {
				$v['Message']['created'] = @date('d/m/Y', strtotime($v['Message']['created']));
	        	$messages[$k] = $v;
	        }
			$this->set('messages', $messages);

		} else {
			$this->Auth->allow();

			$this->set('ext', '.html');

			App::uses('Image', 'Model');
			$Image = new Image();
			App::uses('Category', 'Model');
			$Category = new Category();
			App::uses('News', 'Model');
			$News = new News();

			// Lấy hình slider
			$this->set('sliders', $Image->getAll('slider'));

			// Lấy menu top
			$this->set('navs', $Category->getAll());
			
			$news = $News->getAll(array(), 0, 5);
			if(!empty($news)) {
				$view = new View( $this );
				$Text = $view->loadHelper( 'Text' );
				foreach ($news as $k =>$v) {
					$v['News']['title'] = $Text->truncate($v['News']['title'], 100, array('ellipsis' => '...', 'exact' => false, 'html' => true)); 
					$news[$k] = $v;
				}
			}
			
			// Lấy tin tức mới
			$this->set('lastnews', $news);
		}

		// Set als
		$model = Inflector::singularize($this->name);
		$this->als = $model;
		$this->set('als', $model);
	}

	/**
	 * Change Sort
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_changeSort() {
		if(!empty($this->request->data['id']) && !empty($this->request->data['sort'])) {

			if(!empty($this->request->data['model']))
				$model = trim($this->request->data['model']);
			else {
				$model = Inflector::singularize($this->name);
			}

			App::uses($model, 'Model');
			$M = new $model();

			$M->id = (int)$this->request->data['id'];

			if($M->saveField('sort', (int)$this->request->data['sort']))
				$this->_responseJson(array('code' => 'success'));
			else
				$this->_responseJson(array('code' => 'danger'));
		}
		$this->_responseJson(array('code' => 'danger'));
	}

	/**
     * Upload file
     *
     * @param FileData  meta
     * @return type  meta
     * @access public
     */
    function _upload($file_data, $folder = PUBLIC_IMAGE_DETAIL ) {
        // Upload avatar
        if (!empty($file_data) && $file_data['error'] == 0) {
            $file = $this->File->upload($file_data, null, $folder);

			if($folder === PUBLIC_IMAGE_DETAIL)
            	$this->File->create_thumb($file);

            return $file;
        } else {
            return '';
        }
    }

    /**
	 * Delete, Lock, Unlock
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_changeStatus( $id = null, $status = 5 ) {

		// Get model tu controller
		$model = Inflector::singularize($this->name);

		$liststatus = array(
			4 => 'Unlock',
			5 => 'Lock',
			9 => 'Delete'
		);

		if( in_array( $this->Auth->user('role'), array( 1,2) ) ) {

			if(empty( $id )) {
				$this->Session->setFlash( __('%s member Fail. User Not Found.', $liststatus[$status]), 'error');
			} else {
				$this->$model->id = (int)$id;

				if( $this->$model->saveField('status', (int)$status ) ) {
					$this->Session->setFlash( __('%s member success.', $liststatus[$status]), 'success');
				} else {
					$this->Session->setFlash( __('%s member fail.', $liststatus[$status]), 'error');
				}
			}
		} else {
			$this->Session->setFlash( 'You are not allowed to execute the function of this.', 'error');
		}

		$this->redirect('/admin/'.$this->name);
	}

	/**
     * Response for client
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function _responseJson($data) {
        $this->RequestHandler->setContent('json', 'text/x-json');

        echo json_encode($data);

        exit;
    }

    /**
     * Create condition from post data
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    var $condPost = array();

    function postConditions($data = array(), $key = '', $like_fields = array(), $als = '') {
        $orgi = $key;
        $arr_stop = array('$gt', '$lt', '$gte', '$lte', '$exists');
        $flag = false;
        foreach ($data as $k => $v) {
            if (in_array($k, $arr_stop))
                $flag = true;

            if (empty($orgi)) {
                $key = $k;
            } else {
                if (!$flag)
                    $key = $orgi . '.' . $k;
            }

            if (is_array($v) && !$flag) {

                $this->postConditions($v, $key, $like_fields);
            } else {
                if (in_array($key, $like_fields)) {
                    $this->condPost[$key.' LIKE '] = '%' . $v . '%';
                } else {
                    if ($flag)
                        $this->condPost[$key] = array($k => $v);
                    else
                        $this->condPost[$key] = $v;
                }
            }
        }

        if (!empty($this->params->params['named']['page'])) {
            $this->params->params['named']['page'] = 1;
        }
    }

    /**
     * Remove Empty Conditions
     */
    function _remove_empty_condition() {
        unset($this->request->data['_Token']);

        foreach ($this->request->data as $key => $value) {

            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    if (empty($v)) {
                        unset($this->request->data[$key][$k]);
                    } else if (is_array($v)) {
                        foreach ($v as $k1 => $v1) {
                            if (empty($v1)) {
                                unset($this->request->data[$key][$k][$k1]);
                            } else if (is_array($v1)) {
                                foreach ($v1 as $k2 => $v2) {
                                    if (empty($v2)) {
                                        unset($this->request->data[$key][$k][$k1][$k2]);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                if (empty($value)) {
                    unset($this->request->data[$key]);
                }
            }
        }
    }

    /**
     * Mapping sort fields
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function _mappingFields($fields) {
        if (!empty($fields) && isset($this->params->params['named']['sort'])) {
            $this->params->params['named']['sort'] = @$fields[$this->params->params['named']['sort']];
            $paginate = $this->paginate;
            $paginate['order'] = array($this->params->params['named']['sort'] => $this->params->params['named']['direction']);
            $this->paginate = $paginate;
        }
    }

    /**
     * Chuyen loi tu invalid sang array de xuat len form
     *
     * @param type  meta
     * @return type  meta
     * @access public
     */
    function _getErrorForInvalidJson($errors = null, $model = "") {

        $ret = array();
        if (empty($errors))
            return $ret;

        foreach ($errors as $k => $msg) {
            $k = ucfirst($k);

            // van con mang
            if (empty($msg[0])) {
                foreach ($msg as $k1 => $_msg) {
                    $k1 = strtolower($k1);
                    if (empty($_msg[0])) {
                        foreach ($_msg as $k2 => $_msg2) {
                            $k2 = strtolower($k2);
                            $ret[] = array('id' => $k . $k1 . $k2, 'msg' => $_msg2[0]);
                        }
                    } else
                        $ret[] = array('id' => strtolower($k . $k1), 'msg' => $_msg[0]);
                }
            } else {
                $ret[] = array('id' => strtolower($k), 'msg' => $msg[0]);
            }
        }

        return $ret;
    }
}
